package me.malajis.equipmentprotect;

import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerItemDamageEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import java.util.Objects;

public class BreakListener implements Listener {
    @EventHandler
    public void onBreak(PlayerItemDamageEvent event) {
        if (Main.onEnable.getConfig().getBoolean("Config.BreakListener")) {
            //获取触发者
            Player p = event.getPlayer();
            //获取将要处理的物品
            ItemStack item = event.getItem();
            //最大耐久值
            double maxDurability = item.getType().getMaxDurability();
            //受到本次攻击后的耐久值
            double nowDurability = maxDurability - item.getDurability() - event.getDamage();
            //检查是否带有附魔
            if (item.getItemMeta() != null && item.getItemMeta().hasEnchants()) {
                //检查耐久值是否小于设定的值
                if (nowDurability / maxDurability < Main.onEnable.getConfig().getDouble("Config.Durability")) {
                    event.setCancelled(true);
                    p.sendMessage(Objects.requireNonNull(Main.onEnable.getConfig().getString("Message.breaktip")).replace("&", "§"));
                    //给予负面效果
                    p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 50, 1));
                    p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 30, 255));
                    p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, 30, 255));
                    p.playSound(p.getLocation(), Sound.ENTITY_VILLAGER_NO, 1, 1);
                }
            }
        }
    }
}
